package com.wee.aircoach_user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.bigtotoro.util.SharedPreferencesUtil;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wee.adapter.ActionSelectAdapter1;
import com.wee.entity.IsMy_plan;
import com.wee.entity.Coach_details;
import com.wee.entity.MD5Util;
import com.wee.entity.Play_list;
import com.wee.entity.Project_down;
import com.wee.fragment.find.CourseActivity;
import com.wee.model.ACache;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Solomon on 2015/11/25.
 */
public class CoachPlanActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView coach_name,plan_name,title,nce,zongshu,cishu,lian,itemest,num_btn;
    private ImageView coach_img;
    private LinearLayout linear;
    private ActionSelectAdapter1 actionSelectAdapter1;

    private ListView warm_list,main_list,stretch_list;
    ImageView imageView;
    private Button video_btn,video_bind;
    private HttpHandler handler;
    private ProgressBar download_pb;
    // list集合第几个
    int i = 0;
    int k = 0;
    int h = 0;
    int downNums=0;
    private int exact;
    private JSONObject jo1;
    private ArrayList<Play_list> mdatas = new ArrayList<Play_list>();
    /**下载Media  list **/
    private List<Project_down.Medias> mlist=new ArrayList<Project_down.Medias>();
    /**展示 教师课程list**/
    private List<Project_down.Project_list> mproject=new ArrayList<Project_down.Project_list>();
    private List<Project_down.Project_list> mproject1=new ArrayList<Project_down.Project_list>();
    private List<Project_down.Project_list> mproject2=new ArrayList<Project_down.Project_list>();
    // 缓存
    private ACache mCache;
    // Gson
    private Project_down data1;
    //接口
    private String url_down;
    private String url_list ;
    private String coach_id;
    private ProgressBar my_progress;
    private int  all;

    public interface OnDownFinishListener{
        public void downFinish();
    }
    private OnDownFinishListener onDownFinishListener;

    public OnDownFinishListener getOnDownFinishListener() {
        return onDownFinishListener;
    }

    public void setOnDownFinishListener(OnDownFinishListener onDownFinishListener) {
        this.onDownFinishListener = onDownFinishListener;
    }

    //   跳转的数据
    String  Coach_Id;
    String  Id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coach_plan);
        exact=  SharedPreferencesUtil.getInt(this, com.wee.aircoach_user.Constant.USERTIME);
         Id= getIntent().getStringExtra("CoachDown");
        Coach_Id= getIntent().getStringExtra("teacherId");
        /**下载**/
        url_down = Constant.Down_list+MD5Util.md5(exact)+"&id="+Id;
        /**播放清单*/
        url_list = Constant.PLAYER_LIST+MD5Util.md5(exact)+"&id="+Id+"&ver"+new Random().nextInt(9999);
        /**教练信息**/
        coach_id=Constant.COACH_INFO+MD5Util.md5(exact)+"&id="+Coach_Id;
        initView();
        mCache = ACache.get(CoachPlanActivity.this);

    }
    private void lists() {
        try{
/**展示课程list**/
            for(i=0;i<data1.getWarm().size();i++){
                mproject.add(data1.getWarm().get(i));
            }
            for(i=0;i<data1.getMain().size();i++){
                mproject1.add(data1.getMain().get(i));
            }
            for(i=0;i<data1.getStretch().size();i++){
                mproject2.add(data1.getStretch().get(i));
            }

            if(mproject!=null){
                actionSelectAdapter1 = new ActionSelectAdapter1(this, mproject);
                warm_list.setAdapter(actionSelectAdapter1);
            }
            if(mproject1!=null){
                actionSelectAdapter1 = new ActionSelectAdapter1(this, mproject1);
                main_list.setAdapter(actionSelectAdapter1);
            }
            if(mproject2!=null){
                actionSelectAdapter1 = new ActionSelectAdapter1(this, mproject2);
                stretch_list.setAdapter(actionSelectAdapter1);
            }
        }catch(Exception e){

        }
    }

    private void initView() {
        my_progress= (ProgressBar) findViewById(R.id.my_progress);
        zongshu= (TextView) findViewById(R.id.zongshu);
        lian= (TextView) findViewById(R.id.lian);
        num_btn= (TextView) findViewById(R.id.num_btn);
        cishu= (TextView) findViewById(R.id.cishu);
        linear= (LinearLayout) findViewById(R.id.linear);
         imageView = (ImageView)findViewById(R.id.imagview);
        video_bind= (Button) findViewById(R.id.video_bind);
        video_bind.setOnClickListener(this);
        download_pb = (ProgressBar) findViewById(R.id.download_pb);
        video_btn = (Button)findViewById(R.id.video_btn);
        video_btn.setOnClickListener(this);
        findViewById(R.id.plan_yingyong).setOnClickListener(this);
        plan_name=(TextView)findViewById(R.id.plan_name);
        findViewById(R.id.back).setOnClickListener(this);
        itemest = (TextView) findViewById(R.id.itemest);
        title=(TextView) findViewById(R.id.title);
        nce=(TextView) findViewById(R.id.nce);
        warm_list = (ListView) findViewById(R.id.list_plan_warm);
        main_list = (ListView) findViewById(R.id.list_plan_main);
        stretch_list = (ListView) findViewById(R.id.list_plan_stretch);
        coach_img = (ImageView) findViewById(R.id.coach_photo);
        coach_name = (TextView) findViewById(R.id.cocah_user);
        coach_img.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mproject.clear();
        mproject1.clear();
        mproject2.clear();

        gethttp();
        gethttp1();
        gethttp2();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();

                break;
            case R.id.plan_yingyong:
                Intent intent1= new Intent(CoachPlanActivity.this, VideoViewActivity.class);
                startActivity(intent1);
                break;
            case R.id.video_btn:
                /**下载播放清单*/
                /**下载视频*/
                setOnDownFinishListener(new OnDownFinishListener() {
                    @Override
                    public void downFinish() {
                        downNums = 0;
                        save1();
                    }
                });
                download();
                /**传值跳转*/

                break;
            case R.id.coach_photo:
                Intent intent = new Intent(CoachPlanActivity.this, CoachInfoActivity.class);
                intent.putExtra("Coachid", Coach_Id);
                startActivity(intent);
                break;
            case  R.id.video_bind:
                //绑定计划
                bindplan();
                break;
        }
    }
    private void bindplan() {
        int  it=  SharedPreferencesUtil.getInt(CoachPlanActivity.this, Constant.USERID);
        RequestParams params = new RequestParams();
        params.addBodyParameter("token", ""+MD5Util.md5(exact));
        params.addBodyParameter("userId", ""+it);
        params.addBodyParameter("planId", ""+getIntent().getStringExtra("CoachDown"));
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                Constant.BIND_PLAN,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        JSONObject json;
                        try {

                            json = new JSONObject(str);
                            if(json.getString("status").equals("ok")){
                           //     SharedPreferencesUtil.setInt(CoachPlanActivity.this,Constant.NUM,0);
                              Toast.makeText(CoachPlanActivity.this,"绑定成功",Toast.LENGTH_SHORT).show();
                               video_bind.setVisibility(View.GONE);
                               video_btn.setVisibility(View.VISIBLE);
                            }else{
                             Toast.makeText(CoachPlanActivity.this,"绑定失败",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(CoachPlanActivity.this,"绑定失败",Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void save1() {
        // TODO Auto-generated method stub
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET, url_list,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current,
                                          boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        // textView.setText(responseInfo.result);

                        String t = responseInfo.result;
                        mCache.put("kangning", t);
                        read();
                    }

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });

    }

    private void read( ) {
        // TODO Auto-generated method stub
        String str = mCache.getAsString("kangning");
        if (str != null) {
            try {
                JSONObject jo;
                jo = new JSONObject(str);
                JSONArray jsonArr1 = jo.getJSONArray("data");
                for (int j = 0; j < jsonArr1.length(); j++) {
                    jo1 = jsonArr1.getJSONObject(j);
                    System.out.println("jo1");
                    Play_list tity = new Play_list();
                    tity.setCount(jo1.getInt("count"));
                    tity.setId(jo1.getInt("id"));
                    tity.setType(jo1.getString("type"));
                    tity.setSeq(jo1.getInt("seq"));
                    mdatas.add(tity);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Intent intent = new Intent();
            intent.setClass(CoachPlanActivity.this, VideoViewActivity.class);
            intent.putExtra("kangning", mdatas);
            startActivity(intent);
            mdatas = new ArrayList<Play_list>();
        } else {
            Toast.makeText(CoachPlanActivity.this, "正在缓存数据", Toast.LENGTH_LONG).show();
        }

    }

    private void download() {
        try{
            /**z组成一个下载清单*/
        if(data1.getWarm().size()!=0){
            for(i=0;i<data1.getWarm().size();i++){
                mlist.addAll(data1.getWarm().get(i).getMedias());
            }
            }
       if(data1.getMain().size()!=0){
            for(i=0;i<data1.getMain().size(); i++) {
                mlist.addAll(data1.getMain().get(i).getMedias());
            }
       }
       if (data1.getStretch().size()!=0){
            for(i=0;i<data1.getStretch().size();i++){
                mlist.addAll(data1.getStretch().get(i).getMedias());
            }



       }
/**统计不重复视频的数量*/

            for (int i = 0; i < mlist.size()-1; i++)  //外循环是循环的次数
            {
                for (int j = mlist.size()-1; j > i; j--)  //内循环是 外循环一次比较的次数
                {
                    if (mlist.get(j).getId().equals(mlist.get(i).getId())) {
                        mlist.remove(j);
                    }

                }
            }


            for( k=0;k<mlist.size();k++){
                File file = new File(Environment
                        .getExternalStorageDirectory().getAbsolutePath()
                        + "/VideoAirCache/" + mlist.get(k).getId() + ".mp4");
             if( file.exists()) {
                    //存在
                 downNums++;
                 if(downNums == mlist.size()){
                     if(onDownFinishListener != null){
                         onDownFinishListener.downFinish();
                         video_btn.setText("播放视频");
                     }
                 }

                }else{
                 HttpUtils http = new HttpUtils();
                 handler = http.download(mlist.get(k).getUrl(), Environment
                                 .getExternalStorageDirectory().getAbsolutePath()
                                 + "/VideoAirCache/" + mlist.get(k).getId() + ".mp4",
                         true, false, new RequestCallBack<File>() {
                             @SuppressWarnings("deprecation")
                             @Override
                             public void onStart() {
                             }
                             @Override
                             public void onLoading(long total, long current,
                                                   boolean isUploading) {
                                 super.onLoading(total, current, isUploading);

                             }
                             @Override
                             public void onSuccess(
                                     ResponseInfo<File> responseInfo) {
                                 try{
                                     h++;
                                     if (h<=mlist.size()){
                                         download_pb.setMax(mlist.size());
                                         download_pb.setProgress(h+downNums);
                                         double m= ((double)(int)(h+downNums) / (int)(mlist.size()));

                                         String e= new java.text.DecimalFormat("#.00").format(m*100);
                                         video_btn.setText(e + "%");
                                         if (e.equals("100.00")){
                                             video_btn.setText("播放视频");
                                             if(onDownFinishListener != null){
                                                 onDownFinishListener.downFinish();
                                                 video_btn.setText("播放视频");

                                             }
                                         }
                                     }
                                 }catch(Exception e){
                                     System.out.print("weewewew"+e);
                                 }
                             }
                             @Override
                             public void onFailure(HttpException error,
                                                   String msg) {
                                 System.out.println("msg111111" + msg);

                             }
                         });
             }


            }
        }catch(Exception e ){
            e.printStackTrace();
        }
    }

    /** 解析字段 */
    public void gethttp() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, url_down,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            data1 = gs.fromJson(object, Project_down.class);
                            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(data1.getFigure_preview()
                                    , imageView);
                            plan_name.setText("" + data1.getName());
                            itemest.setText("" + data1.getDiscription());
                            lian.setText("" + data1.getSchedule());
                            int a =data1.getWarm().size();
                            int b =data1.getMain().size();
                            int c =data1.getStretch().size();
                            num_btn.setText((a+b+c)+"");
                            lists();
                        }
                    }
                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println(e.getMessage());
                    }
                });

    }
    /** 解析教练    · */
    public void gethttp1() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, coach_id,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            Coach_details data2 = gs.fromJson(object, Coach_details.class);
                            coach_name.setText("" + data2.getName());
                             nce.setText(""+data2.getSpecialty());
                              title.setText(""+data2.getTitle());

                            if (data2.getFigure() != null && data2.getFigure().length() != 0) {
                                MyApplication.getInstance().getImageLoader().get(data2.getFigure(), ImageLoader.getImageListener(coach_img, R.drawable.noclass_nocoach, R.drawable.noclass_nocoach), 200, 200);
                            }
                        }
                    }
                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println(e.getMessage());
                    }
                });

    }
    /** 判断是否是我的计划*/
    public void gethttp2() {
        int  exact=  SharedPreferencesUtil.getInt(this, com.wee.aircoach_user.Constant.USERTIME);
        int  it=  SharedPreferencesUtil.getInt(CoachPlanActivity.this, Constant.USERID);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET,
                Constant.ISMY_PLAN + "?token=" + MD5Util.md5(exact)+ "&planId=" + getIntent().getStringExtra("CoachDown") + "" + "&userId=" + it +"&ver"+new Random().nextInt(9999),
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            IsMy_plan plan = gs.fromJson(object, IsMy_plan.class);
                            if (plan.getRes().equals("yes")){
                                linear.setVisibility(View.VISIBLE);
                                my_progress.setProgress(plan.getComplete());
                                my_progress.setMax(plan.getPlanCount());
                                cishu.setText(plan.getComplete() + "");
                                zongshu.setText(plan.getPlanCount() + "");
                                video_bind.setVisibility(View.GONE);
                                video_btn.setVisibility(View.VISIBLE);
                            }else{
                                linear.setVisibility(View.GONE);
                                video_bind.setVisibility(View.VISIBLE);
                                video_btn.setVisibility(View.GONE);
                            }
                        }
                    }
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(CoachPlanActivity.this, "有问题", Toast.LENGTH_SHORT).show();
                    }
                });




    }
}
